import json
from ronglian_sms_sdk import SmsSDK
from mycelery.main import app,flask_app
from application import redis

@app.task(name="send_sms", bind=True)
def send_sms(self,mobile,sms_code):
    """发送短信"""
    try:
        with flask_app.app_context():
            sdk = SmsSDK(
                flask_app.config.get("SMS_ACCOUNT_ID"),
                flask_app.config.get("SMS_ACCOUNT_TOKEN"),
                flask_app.config.get("SMS_APP_ID")
            )
            ret = sdk.sendMessage(
                flask_app.config.get("SMS_TEMPLATE_ID"),
                mobile,
                (sms_code, flask_app.config.get("SMS_EXPIRE_TIME") // 60)
            )
            result = json.loads(ret)

            if result["statusCode"] == "000000":
                pipe = redis.pipeline()
                pipe.multi()  # 开启事务
                # 保存短信记录到redis中
                pipe.setex("sms_%s" % mobile, flask_app.config.get("SMS_EXPIRE_TIME"), sms_code)
                # 进行冷却倒计时
                pipe.setex("int_%s" % mobile, flask_app.config.get("SMS_INTERVAL_TIME"), "_")
                pipe.execute()  # 提交事务
            else:
                flask_app.log.error("短信发送失败!\r\n%s" % ret)
                raise Exception
    except Exception as exc:
        # 重新尝试执行失败任务
        print(self.request.retries) # 本次执行的次数
        self.retry(exc=exc, countdown=3, max_retries=5)
